/**
 * linkage - jQuery xui
 *
 * Licensed under the GPL:
 *   http://www.gnu.org/licenses/gpl.txt
 *
 * Copyright 2014 xjb [ beymy.en@gmail.com ]
 *
 */
(function ($) {
    function loadData(target, next, data) {
        var opts = $.data(target, 'linkage').options;
        var parents = data.parents;
        var length = data.length;
        var firstValue = opts.firstValue;
        var firstText = opts.firstText;
        var str = '';
        var i;
        if (firstText) {
            str += '<option value="' + firstValue + '">' + firstText + '</option>';
        }
        var values = [];
        for (i = 0; i < length; i++) {
            values.push(parents[i].val());
        }
        var rows = opts.load.call(target, opts.data, values);
        if ($.isArray(rows)) {
            for (i = 0; i < rows.length; i++) {
                var row = rows[i];
                str += '<option value="' + row.id + '">' + row.text + '</option>';
            }
        }
        next.html(str);
    }



    function bindEvents(target) {
        function change(e) {
            var t = $($.parser.parseOptions(this).next);
            //加载
            loadData(target, t, e.data);

            //清空
            while (t.length > 0) {
                t = $($.parser.parseOptions(t).next);
                t.html('');
            }
        }
        var t = $(target);
        //change事件

        var parents = [];
        var length = 0;

        var prev = t;
        var next = $($.parser.parseOptions(prev).next);
        while (next.length > 0) {
            parents.push(prev);
            length++;
            prev.change({
                parents: parents,
                length: length
            }, change);
            prev = next;
            next = $($.parser.parseOptions(next).next);
        }
    }
    $.fn.linkage = function (options) {
        options = options || {};
        return this.each(function () {
            var state = $.data(this, 'linkage');
            var opts;
            if (state) {
                opts = $.extend(state.options, options);
            } else {
                opts = $.extend({}, $.fn.linkage.defaults, options);
                state = $.data(this, 'linkage', {
                    options: opts
                });
            }
            bindEvents(this);
        });
    };

    $.fn.linkage.defaults = {
        data: null,
        firstValue: '',
        firstText: null,
        load: function () {}
    };
})(jQuery);